package com.fpd.third;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fpd.model.bean.Logistics;
import com.fpd.tools.ConvertUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @desc 测试类
 * @author wujiangbo
 * @date 2019年12月16日 下午2:53:15
 */
@Slf4j
public class EmsTest {
	public static void main(String[] args) {
		// 退回单号：1150743545676、1180990866030、9975617116906
		// 正常单号：1169599245530
		List<Logistics> list = getLogisticsInfo("1150743545676");
		// 开始排序
		// 按时间排序(最新的物流记录在最前面)
		list.sort((Logistics m1, Logistics m2) -> m2.getOperatingTime().compareTo(m1.getOperatingTime()));
		// 结束排序
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Logistics vo = list.get(i);
				System.out.println(vo);
			}
		}
	}

	public static List<Logistics> getLogisticsInfo(String billNo) {
		List<Logistics> list = new ArrayList<Logistics>();
		try {
			String url = "http://211.156.193.140:8000/cotrackapi/api/track/mail/" + billNo;
			HttpRequest request = HttpUtil.createGet(url);
			// 设置验证信息
			Map<String, String> headers = new HashMap<String, String>();
			headers.put("version", "ems_track_cn_3.0");
			headers.put("authenticate", "983C742C16971243E053D2C2020A2852");
			request.addHeaders(headers);
			long beginTIme = System.currentTimeMillis();
			HttpResponse response = request.execute();
			long endTIme = System.currentTimeMillis();
			log.info("根据快递单号查询物流信息---接口花费时长：{}秒", (endTIme - beginTIme) / 1000);
			// 获取状态码
			int status = response.getStatus();
			log.info("根据快递单号查询物流信息，状态码：{}", status);
			if (status == 200) {
				byte[] xmlString = response.bodyBytes();
				// 得到物流信息
				String res = new String(xmlString, "UTF-8");
				log.info("根据快递单号查询物流信息，物流信息：{}", res);
				// 解析物流信息
				JSONObject result_obj = JSONObject.parseObject(res);
				JSONArray jsonArray = result_obj.getJSONArray("traces");
				Logistics logistics = null;
				// 遍历即可，foreach或for循环
				for (Object value : jsonArray) {
					logistics = JSON.parseObject(value.toString(), Logistics.class);
					logistics.setCodeDesc(ConvertUtil.convertCode(logistics.getCode()));
					logistics.setCode2Desc(ConvertUtil.convertCode2(logistics.getCode2()));
					logistics.setRegion(ConvertUtil.convertProvince(logistics.getProvName()));
					list.add(logistics);
				}
			}
		} catch (UnsupportedEncodingException e) {
			log.error("根据快递单号查询物流信息接口-------异常：{}", e);
		}
		// 按时间排序(最新的物流记录在最前面)
		list.sort((Logistics m1, Logistics m2) -> m2.getOperatingTime().compareTo(m1.getOperatingTime()));
		return list;
	}
}
